package com.objectcarpentry.kaylee.ui.controls;



import java.util.regex.Pattern;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;

import com.objectcarpentry.kaylee.FilteredPlaylist;
import com.objectcarpentry.kaylee.AbstractPlaylist;
import com.objectcarpentry.kaylee.IPlayableFilter;
import com.objectcarpentry.kaylee.KayleeFactory;
import com.objectcarpentry.kaylee.ui.KayleeUIListener;
import com.objectcarpentry.kaylee.ui.KayleeUIPlugin;

public class SearchControlContribution extends WorkbenchWindowControlContribution implements KayleeUIListener {

	
	private Text text; 

	// The last playlist that was NOT derived from a search
	private AbstractPlaylist<?> base;
	

	public SearchControlContribution() {
		base = KayleeUIPlugin.getDefault().getPlaylist();
	}
	
	
	public SearchControlContribution(String id) {
		super(id);
	}

	@Override
	protected Control createControl(Composite parent) {
		text = new Text (parent, SWT.SEARCH | SWT.ICON_CANCEL);
		
		text.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				if (text.getText().trim().length() > 0) {
					search(text.getText());
				} else {
					clearSearch();
				}
			}
		});
		
		
		return text;
		
	}
	
	private void search(final String text) {
		System.out.println("searching " + base);
		IPlayableFilter filter = new IPlayableFilter() {
			
			Pattern pattern = Pattern.compile(text, Pattern.CASE_INSENSITIVE);
			
			@Override
			public Pattern getArtist() {
				return pattern;
			}

			@Override
			public Pattern getTitle() {
				return pattern;
			}
		};
		
		FilteredPlaylist filtered = KayleeFactory.eINSTANCE.createFilteredPlaylist();
		filtered.setFilter(filter);
		filtered.setDelegate(base);
		
		KayleeUIPlugin.getDefault().setPlaylist(filtered);
		
	}


	@Override
	public void playlistChanged(AbstractPlaylist<?> playlist) {
		if (! (playlist instanceof FilteredPlaylist)) {
			base = playlist;
			clearSearch();
		}
	}
	
	public void clearSearch(){
		
		
		KayleeUIPlugin.getDefault().setPlaylist(base);
	}
	

}
